package lee.vioson.ebook.ui.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import androidx.navigation.NavHostController
import coil.compose.rememberAsyncImagePainter
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import lee.vioson.composecommon.widgets.Input
import lee.vioson.composecommon.widgets.placeHolder
import lee.vioson.ebook.R
import lee.vioson.ebook.data.AppContainer
import lee.vioson.ebook.ui.AppDestinations
import lee.vioson.ebook.ui.AppTheme
import lee.vioson.ebook.ui.components.dialog.SelectDialog
import lee.vioson.ebook.utils.GlideEngine
import lee.vioson.ebook.viewmodels.FeedbackViewModel
import lee.vioson.remotedata.bean.requestbody.FeedbackBody

/**
 *Author:viosonlee
 *Date:2023/6/12
 *DESCRIPTION:
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun Feedback(
    msgId: String?,
    navHostController: NavHostController,
    appContainer: AppContainer,
    viewModel: FeedbackViewModel = viewModel(factory = viewModelFactory {
        initializer {
            FeedbackViewModel(
                appContainer
            )
        }
    })
) {
    val state by viewModel.state.collectAsState()
    var showDialog by remember { mutableStateOf(false) }

    Scaffold(topBar = {
        TopBar(
            title = stringResource(id = R.string.Feedback),
            navHostController = navHostController,
            action = {
                Icon(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(8.dp)
                        .clickable {
                            navHostController.navigate(AppDestinations.FEEDBACK_HISTORY)
                        },
                    imageVector = Icons.Default.Settings,
                    contentDescription = "feedback history",
                    tint = AppTheme.appColors.whiteText80
                )
            }
        )
    }) { paddingValues ->
        Column(
            modifier = Modifier.padding(paddingValues),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Row(
                Modifier
                    .fillMaxWidth()
                    .height(56.dp)
                    .padding(start = 16.dp, end = 8.dp, top = 8.dp, bottom = 8.dp)
                    .clickable {
                        //to choose a type of feedback
                        showDialog = true
                    },
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = stringResource(id = R.string.Type),
                    fontSize = 14.sp,
                    color = AppTheme.colors.onBackground
                )
                Spacer(modifier = Modifier.weight(1f))
                if (state.type != null) {
                    Text(
                        text = state.type!!.name,
                        fontSize = 14.sp,
                        color = AppTheme.appColors.whiteText80
                    )
                } else {
                    Text(
                        text = stringResource(id = R.string.Choose_a_type),
                        fontSize = 14.sp,
                        color = AppTheme.appColors.hintColor
                    )
                }
                Icon(
                    imageVector = Icons.Default.KeyboardArrowRight,
                    contentDescription = "choose a type of feedback",
                    tint = AppTheme.appColors.whiteText80
                )
            }
            Divider()
            Row(
                Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp)
            ) {
                state.picList.forEachIndexed { index, uploadPic ->
                    Box(contentAlignment = Alignment.TopEnd) {
                        if (uploadPic.isUploaded) {
                            Image(
                                painter = rememberAsyncImagePainter(model = uploadPic.remoteUrl),
                                contentDescription = "feedback pic",
                                modifier = Modifier
                                    .padding(8.dp)
                                    .size(60.dp)
                            )
                        } else {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                Image(
                                    painter = rememberAsyncImagePainter(model = uploadPic.localPath),
                                    contentDescription = "feedback pic",
                                    modifier = Modifier
                                        .padding(8.dp)
                                        .size(60.dp)
                                )
                                if (uploadPic.uploadError) {
                                    Text(
                                        modifier = Modifier
                                            .size(60.dp)
                                            .clickable { viewModel.uploadFile(uploadPic) },
                                        text = stringResource(
                                            id = R.string.Retry
                                        ),
                                        style = TextStyle(
                                            fontSize = 12.sp,
                                            color = AppTheme.appColors.redTextColor,
                                            textAlign = TextAlign.Center
                                        )
                                    )
                                } else {
                                    CircularProgressIndicator(
                                        modifier = Modifier.size(30.dp),
                                        progress = uploadPic.uploadProcess
                                    )
                                }
                            }
                        }
                        Image(
                            painter = painterResource(id = R.mipmap.ic_delete),
                            contentDescription = "delete this pic",
                            modifier = Modifier
                                .size(16.dp)
                                .clickable {
                                    viewModel.sendEvent(FeedbackViewModel.Event.OnDeletePic(index))
                                }
                        )
                    }
                }


                val context = LocalContext.current
                Box(
                    modifier = Modifier
                        .size(72.dp)
                        .padding(8.dp)
                        .border(width = 1.dp, color = AppTheme.appColors.dividerColor)
                        .clickable {
                            //add new image
                            PictureSelector
                                .create(context)
                                .openGallery(SelectMimeType.TYPE_IMAGE)
                                .setSelectionMode(SelectModeConfig.MULTIPLE)
                                .setMaxSelectNum(9)
                                .setImageEngine(GlideEngine.createGlideEngine())
                                .forResult(object : OnResultCallbackListener<LocalMedia> {
                                    override fun onResult(result: ArrayList<LocalMedia>?) {
                                        result
                                            ?.toMutableList()
                                            ?.let { viewModel.onSelectPicList(it) }
                                    }

                                    override fun onCancel() {}
                                })
                        },
                    contentAlignment = Alignment.Center
                ) {
                    Icon(imageVector = Icons.Default.Add, contentDescription = "add new image")
                }
            }
            Spacer(modifier = Modifier.height(8.dp))
            val focusRequester = remember { FocusRequester() }
            val keyboard = LocalSoftwareKeyboardController.current
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp)
                    .padding(horizontal = 16.dp)
                    .clickable {
                        focusRequester.requestFocus()
                        keyboard?.show()
                    }
            ) {
                Input(
                    modifier = Modifier.fillMaxWidth(),
                    inputModifier = Modifier.focusRequester(focusRequester),
                    textStyle = TextStyle(
                        fontSize = 14.sp,
                        color = AppTheme.appColors.whiteText80
                    ),
                    inputTxt = state.inputContent,
                    onValueChange = {
                        viewModel.sendEvent(FeedbackViewModel.Event.OnInputContent(it))
                    },
                    singleLine = false,
                    maxLength = 300,
                    placeholder = placeHolder(id = R.string.Please_enter_your_question)
                )
            }
            Row(
                Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp)
                    .padding(bottom = 2.dp),
                horizontalArrangement = Arrangement.End
            ) {
                Text(
                    text = "${state.inputContent.length}/300",
                    fontSize = 12.sp,
                    color = AppTheme.appColors.hintColor
                )
            }
            Divider()
            Spacer(modifier = Modifier.height(24.dp))
            Button(
                onClick = {
                    if (state.type != null) {
                        viewModel.commit(
                            FeedbackBody(
                                state.inputContent,
                                "",
                                msgId ?: "",
                                state.type!!.name,
                                state.type!!.code,
                                appContainer.uniqueId
                            )
                        )
                    }
                },
                shape = RoundedCornerShape(2.dp),
                enabled = state.enable,
                colors = AppTheme.loginButtonColors()
            ) {
                Text(text = stringResource(id = R.string.Submit))
            }
        }
    }
    if (showDialog) {
        SelectDialog(
            data = viewModel.feedbackTypeList,
            showText = { it.name },
            onDismiss = { showDialog = false },
            select = state.type,
            onConfirm = {
                viewModel.sendEvent(FeedbackViewModel.Event.OnTypeSelect(viewModel.feedbackTypeList[it]))
            })
    }
}